package com.study.example.gameserver.module.backpack.convert;

import com.sparrow.common.util.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.study.example.gameserver.module.backpack.entity.Item;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.concurrent.ConcurrentHashMap;

@Converter(autoApply = false)
public class ItemsConverter implements AttributeConverter<ConcurrentHashMap<Long, Item>, String> {

    @Override
    public String convertToDatabaseColumn(ConcurrentHashMap<Long, Item> attribute) {
        try {
            return JsonUtil.toJSON(attribute);
        } catch (Exception e) {
            throw new IllegalArgumentException("Error converting map to JSON string", e);
        }
    }

    @Override
    public ConcurrentHashMap<Long, Item> convertToEntityAttribute(String dbData) {
        try {
            if (dbData == null || dbData.isEmpty()) {
                return new ConcurrentHashMap<>();
            }
            return JsonUtil.getObjectMapper().readValue(dbData, new TypeReference<ConcurrentHashMap<Long, Item>>() {});
        } catch (Exception e) {
            throw new IllegalArgumentException("Error reading JSON string to map", e);
        }
    }
}

